﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeSwitchEventViewer
{
    internal class InboundSocket
    {
        static ESLconnection _CONN;
        static bool _Runing = true;

        public static void Start(string ip,int port,string pw,Action<string,string> _EventRevCallback,Action complete)
        {
            try
            {
                _Runing = true;
                _CONN = new ESLconnection(ip, port, pw);
                if (_CONN.Connected() == 1)
                {
                    _CONN.Events("plain", "ALL");
                    ESLevent recEvent;
                    while (_Runing)
                    {
                        recEvent = _CONN.RecvEvent();
                        var uuid = recEvent.GetHeader("Unique-ID", -1);
                        var eventName = recEvent.GetHeader("Event-Name", -1);

                        // var plainText = recEvent.Serialize("xml").Replace("%3A",":").Replace("%2F","/").Replace("%3F","?").Replace("%3D", "=").Replace("%26", "&");
                        var plainText = System.Web.HttpUtility.UrlDecode(recEvent.Serialize("xml"));
                        _EventRevCallback($"{eventName}:{uuid}", plainText);
                    }
                }

                _CONN.Dispose();
            }
            catch(Exception ex)
            {
                _EventRevCallback($"EX:{ex.Message}", ex.ToString());
            }
            _Runing= false;
            complete();
        }

        public static void Stop()
        {
            _Runing = false;
            _CONN.Disconnect();
        }
    }
}
